// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SimpleProducerAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Test.Robotics.Runtime
{
    using System;
    using System.Runtime.Serialization;
    using System.Threading;
    using Microsoft.Robotics.Runtime;

    /// <summary>
    /// Producer agent that generates a sequence of numbers. Can be used from code or from manifests.
    /// Use this agent instead of the TimerAgent in test code. 
    /// Also, check out the MessageInjectorAgent class before using this one, it might be a better fit.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Design",
    "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
    Justification = "Agents clean up resources when OnDeactivated() is called")]
    [DataContract]
    public class SimpleProducerAgent : ProducerAgent<SimpleAgentMessage<int>>
    {
        /// <summary>
        /// The length of the sequence to generate.
        /// </summary>
        [DataMember]
        private int count;

        /// <summary>
        /// Indicates the spacing between published messages.
        /// </summary>
        [DataMember]
        private int interval;

        /// <summary>
        /// Internal event used to indicate completion.
        /// </summary>
        private EventWaitHandle completionEvent;

        /// <summary>
        /// True as long as the active is not deactivated
        /// </summary>
        private bool isActive;

        /// <summary>
        /// Producer Thread.
        /// </summary>
        private Thread thread;

        /// <summary>
        /// Initializes a new instance of the SimpleProducerAgent class.
        /// </summary>
        /// <param name="name">The name of the agent instance.</param>
        /// <param name="count">The length of the sequence to generate.</param>
        /// <param name="interval">Indicates the spacing between published messages, in ms. If 0, the agent block when posting a message.</param>
        public SimpleProducerAgent(string name, int count, int interval)
            : base(name)
        {
            this.count = count;
            this.interval = interval;
            this.completionEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
        }

        /// <summary>
        /// Generates the sequence upon activation.
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();
            this.isActive = true;
            this.thread = new Thread(this.Generate);
            this.thread.Name = this.Name;
            this.thread.Start();
        }

        /// <summary>
        /// Generates the sequence upon activation.
        /// </summary>
        public override void OnDeactivated()
        {
            base.OnDeactivated();
            this.isActive = false;
            this.thread.Join();
        }

        /// <summary>
        /// Blocks until the agent has posted its messages.
        /// </summary>
        /// <param name="timeout">timeout in ms</param>
        /// <returns>true if the event was signaled, false if the timeout was reached</returns>
        public bool Wait(int timeout)
        {
            return this.completionEvent.WaitOne(timeout);
        }

        /// <summary>
        /// Generates the messages at a regular cadence
        /// </summary>
        private void Generate()
        {
            for (int i = 0; i < this.count; i++)
            {
                if (!this.isActive)
                {
                    // return rather than break to not set the completion event
                    return;
                }

                this.Publisher.Post(new SimpleAgentMessage<int>(i, AgentMessage.GetCurrentTime()), this.interval == 0);
                Thread.Sleep(this.interval);
            }

            this.completionEvent.Set();
        }
    }
}
